/* Copyright (c) 2006 YourNameHere
   See the file LICENSE.txt for licensing information. */

const Cc = Components.classes;
const Ci = Components.interfaces;


var searchSvc = Cc["@mozilla.org/browser/search-service;1"].getService(Ci.nsIBrowserSearchService);
var appInfo = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULAppInfo);
var shellSvc = Cc["@mozilla.org/browser/shell-service;1"].getService(Ci.nsIShellService);
var sessionStore = Cc["@mozilla.org/browser/sessionstore;1"].getService(Ci.nsISessionStore);
var sessionStartup = Cc["@mozilla.org/browser/sessionstartup;1"].getService(Ci.nsISessionStartup);
var windowMediator = Cc["@mozilla.org/appshell/window-mediator;1"].getService(Ci.nsIWindowMediator);

var defB = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService).getDefaultBranch(null);
var environment = Cc["@mozilla.org/process/environment;1"].getService(Ci.nsIEnvironment);
var promptSvc = Cc["@mozilla.org/embedcomp/prompt-service;1"].getService(Ci.nsIPromptService);

var iniFile = Cc["@mozilla.org/xpcom/ini-parser-factory;1"].getService(Ci.nsIINIParserFactory).createINIParser(iniFile);
var bmSvc = Cc["@mozilla.org/browser/nav-bookmarks-service;1"].getService(Ci.nsINavBookmarksService);
var annoSvc = Cc["@mozilla.org/browser/annotation-service;1"].getService(Ci.nsIAnnotationService);
var livemarkSvc = Cc["@mozilla.org/browser/livemark-service;2"].getService(Ci.nsILivemarkService);
var dirSvc = Cc["@mozilla.org/file/directory_service;1"].getService(Ci.nsIProperties);
var prefSvc = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService);
var iosvc = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);


var ioService = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
var eTLDService = Cc["@mozilla.org/network/effective-tld-service;1"].getService(Ci.nsIEffectiveTLDService);
var idnService = Cc["@mozilla.org/network/idn-service;1"].getService(Ci.nsIIDNService);

var consoleSvc = Cc["@mozilla.org/consoleservice;1"].getService(Ci.nsIConsoleService);
var ioService = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);

const IS_CONTRACTID = "@mozilla.org/widget/idleservice;1";
const OS_CONTRACTID = "@mozilla.org/observer-service;1";
const HS_CONTRACTID = "@mozilla.org/browser/nav-history-service;1";
const BS_CONTRACTID = "@mozilla.org/browser/nav-bookmarks-service;1";
const TS_CONTRACTID = "@mozilla.org/timer;1";
const SB_CONTRACTID = "@mozilla.org/intl/stringbundle;1";
const TIM_CONTRACTID = "@mozilla.org/updates/timer-manager;1";

var bms = Cc[BS_CONTRACTID].getService(Ci.nsINavBookmarksService);
var hs = Cc[HS_CONTRACTID].getService(Ci.nsINavHistoryService);
var os = Cc[OS_CONTRACTID].getService(Ci.nsIObserverService);
var idlesvc = Cc[IS_CONTRACTID].getService(Ci.nsIIdleService);
var dbConn = Cc[HS_CONTRACTID].getService(Ci.nsPIPlacesDatabase).DBConnection;
var bundle = Cc[SB_CONTRACTID].getService(Ci.nsIStringBundleService);
var time = Cc[TIM_CONTRACTID].getService(Ci.nsIUpdateTimerManager);

var ruleNum = Cc["@mozilla.org/intl/stringbundle;1"].getService(Ci.nsIStringBundleService);
var consoleSvc = Cc["@mozilla.org/consoleservice;1"].getService(Ci.nsIConsoleService);
var categoryManager = Cc["@mozilla.org/categorymanager;1"].getService(Ci.nsICategoryManager);
var ss = Cc["@mozilla.org/browser/sessionstartup;1"].getService(Ci.nsISessionStartup);
var as = Cc["@mozilla.org/atom-service;1"].getService(Ci.nsIAtomService);
var loginManager = Cc["@mozilla.org/login-manager;1"].getService(Ci.nsILoginManager);
var mailtoHandler = Cc["@mozilla.org/uriloader/external-protocol-service;1"].getService(Ci.nsIExternalProtocolService).getProtocolHandlerInfo("mailto");
var extHelperAppSvc = Cc["@mozilla.org/uriloader/external-helper-app-service;1"].getService(Ci.nsIExternalHelperAppService);
var permissionmanager = Cc["@mozilla.org/permissionmanager;1"].getService(Ci.nsIPermissionManager);
var textToSubURI = Cc["@mozilla.org/intl/texttosuburi;1"].getService(Ci.nsITextToSubURI);
var clipboard = Cc["@mozilla.org/widget/clipboardhelper;1"].getService(Ci.nsIClipboardHelper);
var ss = Cc["@mozilla.org/browser/search-service;1"].getService(Ci.nsIBrowserSearchService);
var version = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULAppInfo).version;


var appStartup = Cc["@mozilla.org/toolkit/app-startup;1"].getService(Ci.nsIAppStartup);
var em = Cc["@mozilla.org/extensions/manager;1"].getService(Ci.nsIExtensionManager);
var phs = Cc["@mozilla.org/plugin/host;1"].getService(Ci.nsIPluginHost);

var cacheService = Cc["@mozilla.org/network/cache-service;1"].getService(Ci.nsICacheService);
var cookieMgr = Components.classes["@mozilla.org/cookiemanager;1"].getService(Ci.nsICookieManager);
var storageManagerService = Cc["@mozilla.org/dom/storagemanager;1"].getService(Ci.nsIDOMStorageManager);
var globalHistory = Cc["@mozilla.org/browser/global-history;2"].getService(Ci.nsIBrowserHistory);
var formHistory = Cc["@mozilla.org/satchel/form-history;1"].getService(Ci.nsIFormHistory2);
var dlMgr = Cc["@mozilla.org/download-manager;1"].getService(Ci.nsIDownloadManager);
var pwmgr = Cc["@mozilla.org/login-manager;1"].getService(Ci.nsILoginManager);

// clear all auth tokens
var sdr = Cc["@mozilla.org/security/sdr;1"].getService(Ci.nsISecretDecoderRing);
sdr.logoutAndTeardown();

// clear plain HTTP auth sessions
var authMgr = Cc['@mozilla.org/network/http-auth-manager;1'].getService(Ci.nsIHttpAuthManager);
authMgr.clearAll();

var pm = Cc["@mozilla.org/permissionmanager;1"].getService(Ci.nsIPermissionManager);
pm.removeAll();

var cps = Cc["@mozilla.org/content-pref/service;1"].getService(Ci.nsIContentPrefService);
cps.removeGroupedPrefs();

var shellSvc = Cc["@mozilla.org/browser/shell-service;1"].getService(Ci.nsIShellService);
var ww = Cc["@mozilla.org/embedcomp/window-watcher;1"].getService(Ci.nsIWindowWatcher);

var localeService = Cc["@mozilla.org/intl/nslocaleservice;1"].getService(Ci.nsILocaleService);
var systemLocale = localeService.getSystemLocale().getCategory("NSILOCALE_CTYPE").substr(0,3);

var formatter = Cc["@mozilla.org/toolkit/URLFormatterService;1"].getService(Ci.nsIURLFormatter);
var relnotesURL = formatter.formatURLPref("app.releaseNotesURL");


var updates = Cc["@mozilla.org/updates/update-service;1"].getService(Ci.nsIApplicationUpdateService);
var um = Cc["@mozilla.org/updates/update-manager;1"].getService(Ci.nsIUpdateManager);

var dirSvc = Cc["@mozilla.org/file/directory_service;1"].getService(Ci.nsIProperties);
var prefFile = dirSvc.get("ProfDS", Ci.nsIFile);

const PERMISSION_CONTRACTID = "@mozilla.org/permissionmanager;1";
const PREFERENCES_CONTRACTID = "@mozilla.org/preferences-service;1";
const ATOM_CONTRACTID = "@mozilla.org/atom-service;1";

// a number of services I'll need later
// the cache services
const ACCESS_READ = Components.interfaces.nsICache.ACCESS_READ;
const cacheSvc = Components.classes["@mozilla.org/network/cache-service;1"].getService(Ci.nsICacheService);
var httpCacheSession = cacheSvc.createSession("HTTP", 0, true);
httpCacheSession.doomEntriesIfExpired = false;
var ftpCacheSession = cacheSvc.createSession("FTP", 0, true);
ftpCacheSession.doomEntriesIfExpired = false;

function formatDate(datestr, unknown) {
  // scriptable date formatter, for pretty printing dates
  var dateService = Cc["@mozilla.org/intl/scriptabledateformat;1"].getService(Ci.nsIScriptableDateFormat);
  var date = new Date(datestr);
  if (!date.valueOf()) return unknown;

  return dateService.FormatDateTime("", dateService.dateFormatLong, dateService.timeFormatSeconds, date.getFullYear(), date.getMonth() + 1, date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());
}


var eTLDService = Cc["@mozilla.org/network/effective-tld-service;1"].getService(Ci.nsIEffectiveTLDService);

var cd = Cc[CERTIFICATEDIALOGS_CONTRACTID].getService(Ci.nsICertificateDialogs);


/**
 * Return true iff we have cookies for uri
 */
function hostHasCookies(uri) {
  var cookieManager = Cc["@mozilla.org/cookiemanager;1"].getService(Ci.nsICookieManager2);
  return cookieManager.countCookiesFromHost(uri.asciiHost) > 0;
}

/**
 * Return true iff realm (proto://host:port) (extracted from uri) has
 * saved passwords
 */
function realmHasPasswords(uri) {
  var passwordManager = Cc["@mozilla.org/login-manager;1"].getService(Ci.nsILoginManager);
  return passwordManager.countLogins(uri.prePath, "", "") > 0;
}

function getSession() {
    var dragService = Cc["@mozilla.org/widget/dragservice;1"].getService(Ci.nsIDragService);
    return dragService.getCurrentSession();
}

function importFromFile() {
    var fp = Cc["@mozilla.org/filepicker;1"].createInstance(Ci.nsIFilePicker);
    fp.init(window, PlacesUIUtils.getString("SelectImport"), Ci.nsIFilePicker.modeOpen);
    fp.appendFilters(Ci.nsIFilePicker.filterHTML);
    if (fp.show() != Ci.nsIFilePicker.returnCancel) {
      if (fp.file) {
        var importer = Cc["@mozilla.org/browser/places/import-export-service;1"].getService(Ci.nsIPlacesImportExportService);
        var file = fp.file.QueryInterface(Ci.nsILocalFile);
        importer.importHTMLFromFile(file, false);
      }
    }
}

var microsummaries = Cc["@mozilla.org/microsummary/service;1"].getService(Ci.nsIMicrosummaryService);
var RDF = Cc["@mozilla.org/rdf/rdf-service;1"].getService(Ci.nsIRDFService);
var localStore = this.RDF.GetDataSource("rdf:local-store");
var ptm = Cc["@mozilla.org/browser/placesTransactionsService;1"].getService(Ci.nsIPlacesTransactionsService);
var URIFixup = Cc["@mozilla.org/docshell/urifixup;1"].getService(Ci.nsIURIFixup);
var privateBrowsing = Cc["@mozilla.org/privatebrowsing;1"].getService(Ci.nsIPrivateBrowsingService);

var cacheService = Cc["@mozilla.org/network/application-cache-service;1"].getService(Ci.nsIApplicationCacheService);
var storageManager = Cc["@mozilla.org/dom/storagemanager;1"].getService(Ci.nsIDOMStorageManager);

var handlerSvc = Cc["@mozilla.org/uriloader/handler-service;1"].getService(Ci.nsIHandlerService);

var converterSvc = Cc["@mozilla.org/embeddor.implemented/web-content-handler-registrar;1"].getService(Ci.nsIWebContentConverterService);
var mimeSvc = Cc["@mozilla.org/mime;1"].getService(Ci.nsIMIMEService);
var executableType = Cc["@mozilla.org/mime;1"].getService(Ci.nsIMIMEService).getTypeFromExtension("exe");

function reloadPAC()
{
  Cc["@mozilla.org/network/protocol-proxy-service;1"].getService().reloadPAC();
}


var glue = Cc["@mozilla.org/browser/browserglue;1"].getService(Ci.nsIBrowserGlue);
glue.sanitize(window || null);


 /**
   * Returns true if the user has a master password set and false otherwise.
   */
function masterPasswordSet()
{
  var secmodDB = Cc["@mozilla.org/security/pkcs11moduledb;1"].getService(Ci.nsIPKCS11ModuleDB);
  var slot = secmodDB.findSlotByName("");
  if (slot) {
    var status = slot.status;
    var hasMP = status != Ci.nsIPKCS11Slot.SLOT_UNINITIALIZED &&
                status != Ci.nsIPKCS11Slot.SLOT_READY;
    return hasMP;
  } else {
    // XXX I have no bloody idea what this means
    return false;
  }
}


var appContext = Cc["@mozilla.org/safebrowsing/application;1"].getService().wrappedJSObject;

var certdb = Cc[nsX509CertDB].getService(nsIX509CertDB);
var certcache = Cc[nsNSSCertCache].createInstance(Ci.nsINSSCertCache);  
certcache.cacheAllCerts();


var storageService = Cc["@mozilla.org/storage/service;1"].getService(Ci.mozIStorageService);
var mDBConn = storageService.openDatabase(new_file);


var output = "";
var transportService = Components.classes["@mozilla.org/network/socket-transport-service;1"].getService(Components.interfaces.nsISocketTransportService);
var transport = transportService.createTransport(null, 0, host, port, null);

var outstream = transport.openOutputStream(1, 0, 0);
// TRY Seems to work well
var bos = Components.classes["@mozilla.org/binaryoutputstream;1"].createInstance(Components.interfaces.nsIBinaryOutputStream);
bos.setOutputStream(outstream);
// END TRY
bos.write(outputData, outputData.length);

transport.setTimeout(1, timeout);
var stream = transport.openInputStream(1, 100, 100000);

var bis = Components.classes["@mozilla.org/binaryinputstream;1"].createInstance(Components.interfaces.nsIBinaryInputStream);
bis.setInputStream(stream);

var instream = Components.classes["@mozilla.org/scriptableinputstream;1"].createInstance(Components.interfaces.nsIScriptableInputStream);
instream.init(stream);



var json = new Object();
var xmlparser = Cc["@mozilla.org/xmlextras/domparser;1"].getService(Ci.nsIDOMParser);
var parsed_xml = xmlparser.parseFromString(xml, "text/xml");
if (parsed_xml.documentElement.tagName == "parsererror") {
    json;
}


var strBundle = Cc["@mozilla.org/intl/stringbundle;1"].getService(Ci.nsIStringBundleService);
var intlMess = strBundle.createBundle("chrome://global-platform/locale/intl.properties");
intlMess.GetStringFromName("intl.charset.default");

var ds = Cc["@mozilla.org/file/directory_service;1"].getService(Ci.nsIProperties);
var profdir = ds.get("ProfD", Ci.nsILocalFile);


var Clipboard = {
    get clip() {
        return Cc["@mozilla.org/widget/clipboard;1"].getService(Ci.nsIClipboard);
    },
    putString: function(txt) {
        var str = Cc["@mozilla.org/supports-string;1"].createInstance(Ci.nsISupportsString);
        str.data = txt;
        var trans = Cc["@mozilla.org/widget/transferable;1"].createInstance(Ci.nsITransferable);
        trans.addDataFlavor("text/unicode");
        trans.setTransferData("text/unicode", str, txt.length * 2);
        this.clip.setData(trans, null, Ci.nsIClipboard.kGlobalClipboard)
    },
    getString: function() {
        var has_data = clip.hasDataMatchingFlavors(["text/unicode"], 1, Ci.nsIClipboard.kGlobalClipboard);
        if (!has_data) return null;
        var trans = Cc["@mozilla.org/widget/transferable;1"].createInstance(Ci.nsITransferable);
        trans.addDataFlavor("text/unicode");
        this.clip.getData(trans, Ci.nsIClipboard.kGlobalClipboard);
        var str = {},
        len = {};
        trans.getTransferData("text/unicode", str, len);
        str = str.value.QueryInterface(Ci.nsISupportsString);
        txt = str.data.substring(0, len.value / 2);
        return txt;
    }
};


var oClipBoard = Components.classes["@mozilla.org/widget/clipboardhelper;1"].getService(Components.interfaces.nsIClipboardHelper);
oClipBoard.copyString(str);


function sfSpellCheck(theTextBox)
{
	//load the javascript loader
	var loader = Cc["@mozilla.org/moz/jssubscript-loader;1"].getService(Ci.mozIJSSubScriptLoader);
	
	//use the above javascript loader to load the provided spellcheck wrapper
	loader.loadSubScript("chrome://global/content/inlineSpellCheckUI.js", this);
	
	//put the firefox-wide prefs into an object
	//used to get local when adding more dictionaries
	this.prefs = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch);
	
	var doSpellCheck = (this.prefs.getIntPref("layout.spellcheckDefault") == 1);
	
	if (doSpellCheck) {
		this.InlineSpellCheckerUI.init(theTextBox);
		this.InlineSpellCheckerUI.enabled = true;
	}
	else {
		this.hideContextSpellingItems();
	}
}


var dns = Cc["@mozilla.org/network/dns-service;1"].getService(Ci.nsIDNSService);

function getDefaultPath() {
    var file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsILocalFile);
    /* Always use ProfD by default in order to support application-wide installations.
       http://foxyproxy.mozdev.org/drupal/content/tries-use-usrlibfirefox-304foxyproxyxml-linux#comment-974 */
    var dir = Cc["@mozilla.org/file/directory_service;1"].getService(Ci.nsIProperties).get("ProfD", Ci.nsILocalFile);
    file.initWithPath(dir.path);
    file.appendRelativePath("foxyproxy.xml");
    return file;
}



var fileProtocolHandler = Cc["@mozilla.org/network/protocol;1?name=file"].getService(Ci["nsIFileProtocolHandler"]);

var proxyService = Cc["@mozilla.org/network/protocol-proxy-service;1"].getService(Ci.nsIProtocolProxyService), DEFAULT_COLOR = "#65BAD7";

  
function getBlockedPageMatch(exp) {
    // doc.createNSResolver(doc) fails on FF2 (not FF3), so we use an instance of nsIDOMXPathEvaluator instead
    // of the next line
    // var n = doc.evaluate(exp, doc, doc.createNSResolver(doc), doc.ANY_TYPE, null).iterateNext();

    // new XPathEvaluator() is not yet available; must go through XPCOM
    var xpe = Cc["@mozilla.org/dom/xpath-evaluator;1"].getService(Ci.nsIDOMXPathEvaluator);
    // FF 2.0.0.14: iterateNext is not a function
    var n = xpe.evaluate(exp, doc, xpe.createNSResolver(doc), xpe.FIRST_ORDERED_NODE_TYPE, null);
    n.QueryInterface(CI.nsIDOMXPathResult); // not necessary in FF3, only 2.x and possibly earlier
    return n.iterateNext();
}


 //Mozila drag and drop helpers
Cc['@mozilla.org/moz/jssubscript-loader;1'].getService(Ci.mozIJSSubScriptLoader).loadSubScript('chrome://global/content/nsDragAndDrop.js');

Cc['@mozilla.org/moz/jssubscript-loader;1'].getService(Ci.mozIJSSubScriptLoader).loadSubScript('chrome://global/content/nsTransferable.js');




  
  





















